package com.yssoft.service.supervise;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.yssoft.entity.production.TLabels;
import com.yssoft.entity.production.TPackageCode;
import com.yssoft.mapper.core.TProductsMapper;
import com.yssoft.mapper.inventory.TInstockMapper;
import com.yssoft.mapper.production.TBatchMapper;
import com.yssoft.mapper.production.TLabelsMapper;
import com.yssoft.mapper.production.TPackageCodeMapper;
import com.yssoft.mapper.production.TWorksheetMapper;
import com.yssoft.mapper.sales.TSellGoodsMapper;
import com.yssoft.mapper.supplier.TraceabilityQueryMapper;
import com.yssoft.utils.LayuiUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @类名称: FlowQueryService
 * @类描述: 流向查询service
 * @作者:洪丰
 * @创建时间:2018年6月14日 上午8:45:11
 */
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
@Service
public class FlowQueryService
{
	@Autowired
	private TProductsMapper productsMapper;
	@Autowired
	private TWorksheetMapper worksheetMapper;
	@Autowired
	private TInstockMapper instockMapper;
	@Autowired
	private TSellGoodsMapper sellGoodsMapper;
	@Autowired
	private TLabelsMapper labelsMapper;
	@Autowired
	private TPackageCodeMapper packageCodeMapper;
	@Autowired
	private TraceabilityQueryMapper traceabilityQueryMapper;
	@Autowired
	private TBatchMapper batchMapper;

	/**
	 * @方法名称: queryPurInfo
	 * @功能描述: 获取商品详细信息
	 * @				作者: 洪丰
	 * @创建时间:2018年6月14日 上午9:34:23
	 * @param proId
	 * @param worksheetId
	 * @return Map<String,Object>
	 */
	public Map<String, Object> queryPurInfo(Integer batchId) {
        Map<String,Object> purMap = productsMapper.selectProInfoByProId(batchId);
        return purMap;
    }

	/**
     * 依据产品ID计算配料名称（排除包材和半成品）
     */
    public Map<String, String> queryIngredientsByProId(Integer proId) {
        Map<String, String> result = new HashMap<>();
        if (proId == null) {
            result.put("mName", "");
            result.put("sName", "");
            return result;
        }
        // 物料：排除 create_code = '1' 的包材
        List<Map<String, Object>> materialList = productsMapper.selectMaterialByProId(proId);
        List<String> materialNames = new ArrayList<>();
        if (materialList != null) {
            for (Map<String, Object> item : materialList) {
                Object createCode = item.get("create_code");
                Object name = item.get("name");
                if (name == null) continue;
                if (createCode != null && "1".equals(String.valueOf(createCode))) {
                    continue; // 跳过包材
                }
                materialNames.add(String.valueOf(name));
            }
        }
        // 不查询半成品，只返回物料
        result.put("mName", String.join(",", materialNames));
        result.put("sName", "");
        return result;
    }

	/**
	 * @方法名称: queryWorksheetList
	 * @功能描述: 获取加工单及其流向信息
	 * @作者: 洪丰
	 * @创建时间:2018年6月14日 上午10:53:28
	 * @param batchId
	 * @return List<Map<String,Object>>
	 */
	public List<Map<String, Object>> queryWorksheetList(Integer batchId, Integer proId, String worksheetDate, Integer worksheetId) {
		Map<String,Object> param1 = new HashMap<String,Object>();
		param1.put("batchId", batchId);
		param1.put("worksheetDate", worksheetDate);
		param1.put("worksheetId", worksheetId);
        List<Map<String,Object>> worksheetList = worksheetMapper.selectworksheetByBatchId(param1);
        for(Map<String,Object> wMap : worksheetList){
        	if(null == wMap){
        		continue;
        	}
        	List<Map<String,Object>> instockList =
    				instockMapper.selectInstockByWorksheetId(Integer.parseInt(wMap.get("wId").toString()));
    		wMap.put("instockList", instockList);
    		for(Map<String,Object> insMap : instockList){
    			if(null == insMap){
            		continue;
            	}
    			Map<String,Object> param = new HashMap<String, Object>();
    			param.put("instockId", insMap.get("iId"));
    			param.put("proId", proId);
    			List<Map<String,Object>> sellGoodsList=
    					sellGoodsMapper.selectSellGoodByInstockId(param);
    			insMap.put("sellGoodsList", sellGoodsList);
    		}
         }
        return worksheetList;
	}

	/**
	 * @方法名称: queryFlowMap
	 * @功能描述: 通过标签码获取全部流向信息
	 * @作者: 洪丰
	 * @创建时间:2018年6月14日 下午6:49:52
	 * @param code
	 * @return Map<String,Object>
	 */
	public Map<String, Object> queryFlowMap(String code) {
		Map<String,Object> flowMap = new HashMap<String, Object>();
		TLabels record = new TLabels();
		record.setCode(code);
		record.setDeleteFlag("0");
		TLabels lEntity = labelsMapper.selectOne(record);
		if(null == lEntity){
			return flowMap;
		}
		if(lEntity.gettWorksheeId() == null && lEntity.gettPackageId() == null){
			return flowMap;
		}
		Map<String,Object> param = new HashMap<String, Object>();
		param.put("labelId", lEntity.getId());
		if(lEntity.gettWorksheeId() != null){
			param.put("worksheetId", lEntity.gettWorksheeId());
		}else{
			TPackageCode pEntity = packageCodeMapper.selectByPrimaryKey(lEntity.gettPackageId());
			if(pEntity == null || pEntity.gettWorksheeId() == null){
				return flowMap;
			}
			param.put("worksheetId", pEntity.gettWorksheeId());
		}
		List<Map<String, Object>> resultList = labelsMapper.selectFlowinfoByIdAndWid(param);
		if(resultList != null && resultList.size() > 0){
			flowMap = resultList.get(0);
		}
		return flowMap;
	}

	/**
	 * @方法名称: queryBatchByProId
	 * @功能描述: 根据产品id获取批次
	 * @作者: 洪丰
	 * @创建时间:2018年6月15日 上午11:40:34
	 * @param proId
	 * @return List<Map<String,Object>>
	 */
	public List<Map<String, Object>> queryBatchByProId(String proId, String batchCode) {
		Map<String,Object> param = new HashMap<String, Object>();
		param.put("batchCode", batchCode);
		param.put("proId", proId);
		List<Map<String, Object>> batchList = Lists.newArrayList();
		if(!"".equals(batchCode)){
			batchList = batchMapper.queryBatchListByProId(param);
		}
		return batchList;	}

	/**
	 * @方法名称: queryPurchaseDate
	 * @功能描述: 根据批次id获取加工单加工时间
	 * @作者: 洪丰
	 * @创建时间:2018年6月15日 下午1:35:32
	 * @param batchId
	 * @return JSONObject
	 */
	public JSONObject queryPurchaseDate(Integer batchId) {
        List<Map<String,Object>> purDateList = batchMapper.querypDateListBybatchId(batchId);
        JSONObject jsonObject =LayuiUtil.getJSONObjectByMap(purDateList,0,"","");
        return jsonObject;
   }

	/**
	 * @方法名称: queryAllPurchaseDate
	 * @功能描述: 查询所有生产日期
	 * @作者: 系统
	 * @创建时间:2025年
	 * @return JSONObject
	 */
	public JSONObject queryAllPurchaseDate() {
        List<Map<String,Object>> purDateList = batchMapper.queryAllPurchaseDate();
        JSONObject jsonObject =LayuiUtil.getJSONObjectByMap(purDateList,0,"","");
        return jsonObject;
   }

	/**
	 * @方法名称: querybatchList
	 * @功能描述: 获取批次列表
	 * @作者: 洪丰
	 * @创建时间:2018年6月15日 下午2:51:49
	 * @param proId
	 * @return JSONObject
	 */
	public JSONObject querybatchList(int pageNumber, int pageSize, Integer proId) {
		PageHelper.startPage(pageNumber,pageSize);//下面第一个查询结果进行分页
		Map<String,Object> param = new HashMap<String, Object>();
		param.put("proId", proId);
		// 执行查询，SQL中已处理proId为null的情况（查询所有批次）
		List<Map<String, Object>> batchList = batchMapper.queryBatchListByProId(param);
		int count = batchMapper.queryCountByProId(param);
        JSONObject jsonObject =LayuiUtil.getJSONObjectByMap(batchList,count,"","");
        return jsonObject;
    }
}
